package com.hiabr.iep.common.domain.context;

import com.hiabr.iep.common.domain.constant.CommonConstant;
import com.hiabr.iep.common.domain.vo.req.BaseAdminReq;
import com.hiabr.iep.common.domain.vo.req.BaseUserReq;

import java.util.HashMap;
import java.util.Map;

/**
 * description: ThreadLocalContext
 */
public class ThreadLocalContext {

    /**
     * 使用InheritableThreadLocal便于在主子线程间传递参数
     */
    private static final ThreadLocal<Map<String, Object>> context = new InheritableThreadLocal<>();

    public static void set(String key, Object value) {
        Map<String, Object> map = context.get();
        if (map == null) {
            map = new HashMap<>();
        }
        map.put(key, value);
        context.set(map);
    }

    public static void remove() {
        context.remove();
    }

    public static String getTraceId() {
        Map<String, Object> map = context.get();
        Object traceIdObj = map == null ? null : map.get(CommonConstant.TRACE_ID);
        return traceIdObj == null ? null : traceIdObj.toString();
    }

    public static void setTraceId(String traceId) {
        set(CommonConstant.TRACE_ID, traceId);
    }

    public static BaseAdminReq getAdmin() {
        Map<String, Object> map = context.get();
        Object adminObj = map == null ? null : map.get(CommonConstant.ADMIN);
        return adminObj == null ? null : (BaseAdminReq) adminObj;
    }

    public static void setAdmin(BaseAdminReq admin) {
        set(CommonConstant.ADMIN, admin);
    }

    public static BaseUserReq getUser() {
        Map<String, Object> map = context.get();
        Object userObj = map == null ? null : map.get(CommonConstant.USER);
        return userObj == null ? null : (BaseUserReq) userObj;
    }

    public static void setUser(BaseUserReq user) {
        set(CommonConstant.USER, user);
    }

}
